package com.lc.zpyh.widget;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.toast.ToastUtils;
import com.lc.zpyh.R;
import com.lc.zpyh.http.request.PublicMsgBean;
import com.lc.zpyh.http.request.ReceiveCouponsApi;
import com.lc.zpyh.http.request.SelectCounpByCanteenIdApi;
import com.lc.zpyh.http.response.SelectCanteenBySchoolBean;
import com.lc.zpyh.http.response.SelectCounpByCanteenIdBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.ui.activity.home.SelectMerchantsFlActivity;
import com.lc.zpyh.util.BigDecimalUtils;
import com.lc.zpyh.util.SPUtil;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.ButterKnife;

public class CollectCouponsDialog extends Dialog implements View.OnClickListener{

    private Context context;
    private ImageView img_close;

    private RecyclerView rv_coupon;
    private RecyclerView rv_cantee;
    List <SelectCanteenBySchoolBean.ListBean>  canteeList=new ArrayList<>();
    List<SelectCounpByCanteenIdBean.CouponsBean> dataarrtBeanList =new ArrayList<>();
    private CollectCouponsDialog.OnGoodsOrderListener onGoodsOrderListener;
    private BaseQuickAdapter<SelectCounpByCanteenIdBean.CouponsBean, BaseViewHolder> couponAdapter;
    private BaseQuickAdapter<SelectCanteenBySchoolBean.ListBean, BaseViewHolder> canteeAdapter
            ;
    private String price;
    private String id;
    private String name;

    public CollectCouponsDialog(Context context,List<SelectCanteenBySchoolBean.ListBean> canteeList) {
        super(context, R.style.dialog);
        this.context = context;
        this.canteeList = canteeList;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        Window window = getWindow();
        window.setGravity(Gravity.CENTER); // 此处可以设置dialog显示的位置为居中
//        window.setWindowAnimations(R.style.bottom_menu_animation); // 添加动画效果
        setContentView(R.layout.dialog_collectcoupons);
        WindowManager windowManager = ((Activity) context).getWindowManager();
//        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        DisplayMetrics d = context.getResources().getDisplayMetrics(); // 获取屏幕宽、高
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.width = (int) (d.widthPixels * 0.8);
        getWindow().setAttributes(lp);
        setCanceledOnTouchOutside(true);// 点击Dialog外部消失

        initView();


    }
    private void initView() {
        rv_cantee= findViewById(R.id.rv_cantee);
        rv_coupon = findViewById(R.id.rv_coupon);
        img_close = findViewById(R.id.img_close);

        img_close.setOnClickListener(this);
                    if (canteeList.size()>0){
                        canteeList.get(0).setGrop(true);
                    }
                    canteeAdapter = new BaseQuickAdapter<SelectCanteenBySchoolBean.ListBean,
                            BaseViewHolder>(R.layout.item_coupon_selected, canteeList) {

                        @Override
                        protected void convert(BaseViewHolder holder, SelectCanteenBySchoolBean.ListBean bean) {

                            if (bean.isGrop()) {
                                holder.setVisible(R.id.indicatorBar, true);
                                id = bean.getId()+"";
                                name = bean.getName();
                                coupon(bean.getId() + "",bean.getName());

                            }else {
                                holder.setVisible(R.id.indicatorBar, false);

                            }
                            holder.setText(R.id.tv_type, bean.getName());
                        }


                    };

                    rv_cantee.setAdapter(canteeAdapter);

                    canteeAdapter.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                            for (SelectCanteenBySchoolBean.ListBean bean :canteeList){
                                bean.setGrop(false);
                            }
                            SelectCanteenBySchoolBean.ListBean bean= canteeList.get(position);
                            bean.setGrop(!bean.isGrop());
//                            if (bean.isGrop()) {
//                                school = dataschoolBeanList.get(position).getSchoolName();
//                                schoolid = dataschoolBeanList.get(position).getSchoolId() + "";
//
//                            }
                            canteeAdapter.notifyDataSetChanged();
                        }
                    });

        couponAdapter = new BaseQuickAdapter<SelectCounpByCanteenIdBean.CouponsBean,
                BaseViewHolder>(R.layout.item_coupon, dataarrtBeanList) {

            @Override
            protected void convert(BaseViewHolder baseViewHolder, SelectCounpByCanteenIdBean.CouponsBean dataBean) {
                baseViewHolder.setText(R.id.tv_address, dataBean.getName());
                baseViewHolder.setText(R.id.tv_money, BigDecimalUtils.div(dataBean.getCreditFor() + "", "100", 2));
                baseViewHolder.setText(R.id.tv_date, Html.fromHtml("满" + BigDecimalUtils.div(dataBean.getMeetTheConditions() + "", "100", 0) + "可用 <br>有效天数：" + dataBean.getCouponEffectiveTime()+"天<br/>"));
                if (dataBean.getGetSart() == 0) {
                    baseViewHolder.setVisible(R.id.tv_lingqu, true);
                    baseViewHolder.setGone(R.id.ll_to_make, true);
                } else {
                    baseViewHolder.setGone(R.id.tv_lingqu, true);
                    baseViewHolder.setVisible(R.id.ll_to_make, true);
                }
                baseViewHolder.getView(R.id.ll_to_make).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        context.startActivity(new Intent(context, SelectMerchantsFlActivity.class).putExtra("canteenId",id+"").putExtra("flid", "0").putExtra("schoolid", SPUtil.get(context,IntentKey.ADDRESSID,"") ).putExtra("title", name));
                    }
                });

                baseViewHolder.getView(R.id.tv_lingqu).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        lingqu(dataBean.getCouponId() + "");
                    }
                });


            }


        };

     couponAdapter.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {


            if (onGoodsOrderListener != null) {
                onGoodsOrderListener.onBuyNow(price);
                dismiss();
            }

        }
    });
    View emptyview = View.inflate(context, R.layout.empty_emptylayout, null);

     couponAdapter.setEmptyView(emptyview);

     rv_coupon.setAdapter(couponAdapter);
                }





    private void coupon(String s,String Name) {
        EasyHttp.post(new ApplicationLifecycle())
                .api(new SelectCounpByCanteenIdApi().setId(s).setPageNum("1").setPageSize("999").setType("1").setUserId(SPUtil.get(context, IntentKey.USERID,""))).request(new OnHttpListener<SelectCounpByCanteenIdBean>() {

            @Override
            public void onSucceed(SelectCounpByCanteenIdBean data) {
 if ( data.getCode()==0) {
     dataarrtBeanList.clear();
     dataarrtBeanList.addAll(data.getCoupons());
     for (int i = 0; i < dataarrtBeanList.size(); i++) {
         dataarrtBeanList.get(i).setName(Name);
     }
        couponAdapter.setNewData(dataarrtBeanList);
     couponAdapter.notifyDataSetChanged();
 }
 }

            @Override
            public void onFail(Exception e) {


            }
        });


    }
    private void lingqu(String couponId) {
        EasyHttp.post(new ApplicationLifecycle())
                .api(new ReceiveCouponsApi().setCouponId(couponId).setUserId(SPUtil.get(context, IntentKey.USERID, ""))).request(new OnHttpListener<PublicMsgBean>() {

            @Override
            public void onSucceed(PublicMsgBean data) {
                if (data.getCode()==0) {
                    ToastUtils.show("领取成功");
                    coupon(id + "",name);
                }else {
                    ToastUtils.show(data.getMsg());
                }
            }

            @Override
            public void onFail(Exception e) {


            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.img_close:


                dismiss();
                break;



            default:
                break;
        }
    }
    public interface OnGoodsOrderListener {
        void onDismiss( String time);


        void onBuyNow( String time);


    }

    public void setOnGoodsOrderListener(CollectCouponsDialog.OnGoodsOrderListener onGoodsOrderListener) {
        this.onGoodsOrderListener = onGoodsOrderListener;
    }
}
